<?php

namespace app\common\model;

use think\Model;
use think\Db;

/**
 * 交易模型
 */
class Bill extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    protected static function init()
    {
    }

    /**
     * 赠送宠物
    */
    public static function give($uid, $to_uid, $goods_id, $num)
    {
        if ($to_uid == $uid) {
            return ['error' => 1, 'msg' => '您赠送给自己是没有意义的'];
        }

        $order_goods = Db::name('goods_order')->where(['uid' => $uid, 'goods_id' => $goods_id])->find();
        if ($order_goods['num'] <= 0) {
            return ['error' => 1, 'msg' => '你的背包里还没有此宠物'];
        } elseif ($order_goods['num'] < $num) {
            return ['error' => 1, 'msg' => '你的宠物数量不够赠送数量'];
        } else {
            Db::startTrans();
            try {
                $res = Db::name('goods_order')->where(['id' => $order_goods['id']])->setDec('num', $num);
                if ($res) {
                    if ($order_goods['num'] == 1) {
                        Db::name('goods_order')->where(['id' => $order_goods['id']])->delete();
                    }
                    $exist = Db::name('goods_order')->where(['uid' => $to_uid, 'goods_id' => $goods_id, 'm_status' => 0])->find();
                    if ($exist) {
                        Db::name('goods_order')->where(['id' => $exist['id']])->setInc('num', $num);
                    } else {
                        $goods = model('goods')->where(['id' => $goods_id])->find();
                        $data = [
                            'uid' => $to_uid,
                            'goods_id' => $goods['id'],
                            'name' => $goods['name'],
                            'image' => $goods['image'],
                            'price' => $goods['price'],
                            'buy_coin_id' => $goods['buy_coin_id'],
                            'createtime' => time(),
                            'updatetime' => time(),
                            'status' => 'normal',
                            'num' => 1
                        ];
                        Db::name('goods_order')->insertGetId($data);
                    }
                    \app\common\model\Wallet::up_coin($uid, 0, $goods['buy_coin_id'], 'give_pets');
                    \app\common\model\Wallet::up_coin($to_uid, 0, $goods['buy_coin_id'], 'by_give_pets');

                    Db::commit();
                    return ['error' => 0];
                } else {
                    Db::rollback();
                    return ['error' => 1, 'msg' => '赠送失败'];
                }
            } catch (\Exception $exception) {
                Db::rollback();
                return ['error' => 1, 'msg' => $exception->getMessage()];
            }
        }
    }

    /**
     * 挂卖宠物
    */
    public static function sell($uid, $goods_id, $num, $price)
    {
        $order_goods = Db::name('goods_order')->where(['goods_id' => $goods_id, 'uid' => $uid])->find();
        if (!$order_goods) {
            return ['error' => 1, 'msg' => '您还没有此宠物'];
        } elseif ($order_goods['num'] < $num) {
            return ['error' => 1, 'msg' => '您的宠物数量不足'];
        } elseif ($price <= 0) {
            return ['error' => 1, 'msg' => '挂卖价格错误'];
        } else {
            $res = Db::name('goods_order')->where(['id' => $order_goods['id']])->setDec('num', $num);
            if ($res) {
                $coin_id = 3;//以usdt交易
                $bill_id = TradeOrder::add_bill($uid, '', $order_goods['id'], $num, round($price * $num, 2), $coin_id, 0,  'sell_pets', 0);
                if ($bill_id > 0) {
                    $res = Wallet::up_coin($uid, $price, $coin_id, 'sell_pets', $bill_id);
                    if ($res['error'] > 0) {
                        return ['error' => 1, 'msg' => $res['msg']];
                    } else {
                        return ['error' => 0, 'msg' => '挂卖成功'];
                    }
                } else {
                    return ['error' => 1, 'msg' => '扣宠物数量失败'];
                }
            } else {
                return ['error' => 1, 'msg' => '挂卖失败'];
            }
        }
    }

    /**
     * 购买宠物
     * 买家扣币，买家加订单，卖家加币，卖家减订单
    */
    public static function buy_pets($uid, $tradeid, $num)
    {
        $trade = TradeOrder::get($tradeid);
        if (!$trade) {
            return ['error' => 1, 'msg' => '挂卖订单不存在'];
        } elseif ($num > $trade['num']) {
            return ['error' => 1, 'msg' => '购买数量不能大于挂卖数量'];
        } elseif ($uid == $trade['uid']) {
            return ['error' => 1, 'msg' => '购买自己挂卖的宠物是没有意义的'];
        } elseif ($trade['status'] == 1) {
            return ['error' => 1, 'msg' => '该订单已完成'];
        } elseif ($trade['status'] == 0) {
            $balance = model('wallet')->where(['uid' => $uid, 'coin_id' => config('usdt_id')])->value('balance');
            if ($balance < $trade['amount']) {
                return ['error' => 1, 'msg' => '您的余额不足'];
            } else {
                $order_goods = Db::name('goods_order')->where(['id' => $trade['tradeid']])->find();
                if (!$order_goods) {
                    return ['error' => 1, 'msg' => '挂卖订单源错误'];
                }
                Db::startTrans();
                try {
                    Wallet::up_coin($uid, -$trade['amount'], config('usdt_id'), 'buy_pets', $trade['id']);
                    Wallet::up_coin($trade['uid'], $trade['amount'], config('usdt_id'), 'buy_pets', $trade['id']);
                    $exist_id = Db::name('goods_order')->where(['uid' => $uid, 'goods_id' => $order_goods['goods_id']])->value('id');
                    if ($exist_id) {
                        Db::name('goods_order')->where(['id' => $exist_id])->setInc('num', $num);
                    } else {
                        $data = [
                            'uid' => $uid,
                            'goods_id' => $order_goods['goods_id'],
                            'name' => $order_goods['name'],
                            'image' => $order_goods['image'],
                            'price' => $order_goods['price'],
                            'buy_coin_id' => $order_goods['buy_coin_id'],
                            'createtime' => time(),
                            'updatetime' => time(),
                            'status' => 'normal',
                            'num' => 1
                        ];
                        Db::name('goods_order')->insertGetId($data);
                    }
                    Db::name('goods_order')->where(['id' => $trade['tradeid']])->setDec('num', $num);
                    Db::name('trade_order')->where(['id' => $trade['id']])->update(['status' => 1, 'to_uid' => $uid]);

                    Db::commit();
                } catch (\Exception $exception) {
                    Db::rollback();
                    return ['error' => 1, 'msg' => $exception->getMessage()];
                }
            }
        } else {
            return ['error' => 1, 'msg' => '订单状态错误，无法购买'];
        }

        return ['error' => 0, 'data' => []];
    }
}
